package com.wwwc.index.web.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.*;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.http.*;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

public class SendMailServlet extends HttpServlet {
   public void doGet(HttpServletRequest request,  HttpServletResponse response)
	throws IOException, ServletException 
    {
	doPost(request, response);
	return;
    }

    public void doPost(HttpServletRequest request,
                       HttpServletResponse response)
        throws IOException, ServletException
    {
	PrintWriter writer  = response.getWriter();
        String action       = request.getParameter("action");
	String user_ip      = request.getRemoteAddr();
	
	HttpSession session = request.getSession(true);
	ResourceBundle SystemInfo = (ResourceBundle)session.getAttribute("SystemInfo");
	
	if (SystemInfo == null) {
	    Locale locale = request.getLocale();
	    SystemInfo = ResourceBundle.getBundle("SystemInfo", locale); 
	    session.setAttribute("SystemInfo", SystemInfo);
	}

	String local_ips = SystemInfo.getString("3wcenter.local_ips");
	String database  = SystemInfo.getString("3wcenter.database");

	if (action == null) {
	    String from    = request.getParameter("mailfrom");
	    String to      = request.getParameter("mailto");
	    String subject = request.getParameter("mailsubject");
	    String content = request.getParameter("mailcontent");

	    if ((from == null) || (to == null) || (subject == null) || (content == null)) {
		RequestDispatcher rd = getServletContext().getRequestDispatcher("/jsp/mail/sendmail.jsp");
		rd.forward(request, response);
		return;
	    }

	    // Prepare the beginning of our response
	    response.setContentType("text/html");
	    writer.println("<html>");
	    writer.println("<head>");
	    writer.println("<title>Example Mail Sending Results</title>");
	    writer.println("</head>");
	    writer.println("<body bgcolor=\"white\">");

	    try {
		//for authentication use
		Properties properties = new Properties(); 
		properties.put("mail.smtp.host", "localhost"); 
		properties.put("mail.smtp.auth", "true"); 

		// Acquire our JavaMail session object
		Context initCtx = new InitialContext();
		Context envCtx = (Context) initCtx.lookup("java:comp/env");
		Session session_m = (Session) envCtx.lookup("mail/Session");
		//Session session_m = Session.getDefaultInstance(properties, new SmtpAuthenticator());
		Session user_session_m = session_m.getInstance(properties, new SmtpAuthenticator());

		//Message message = new Message(session_m); 

		// Prepare our mail message
		Message message = new MimeMessage(user_session_m);
		message.setFrom(new InternetAddress(from));
		InternetAddress dests[] = new InternetAddress[] { new InternetAddress(to) };
		message.setRecipients(Message.RecipientType.TO, dests);
		message.setSubject(subject);
		message.setContent(content, "text/plain");
		Transport.send(message);

		// Report success
		writer.println("<strong>Message successfully sent!</strong>");
		//session_m = Session.getDefaultInstance(properties, null); 

	    } catch (Exception e) {

		writer.println("<font color=\"red\">");
		writer.println("ENCOUNTERED EXCEPTION:  " + e);
		writer.println("<pre>");
		e.printStackTrace(writer);
		writer.println("</pre>");
		writer.println("</font>");
	    }

	    // Prepare the ending of our response
	    writer.println("<br><br>");
	    writer.println("<a href=\"jsp/mail/sendmail.jsp\">Create a new message</a><br>");
	    writer.println("<a href=\"jsp/index.html\">Back to examples home</a><br>");
	    writer.println("</body>");
	    writer.println("</html>");        
	}
	else if (action.equals("Send-Message")) {
	    String from    = request.getParameter("mailfrom");
	    String to      = request.getParameter("mailto");
	    String subject = request.getParameter("mailsubject");
	    String content = request.getParameter("mailcontent");

	    if ((from == null) || (to == null) || (subject == null) || (content == null)) {
		writer.println("You need send something. Do you??");
		return;
	    }

	    content = "****************************************\n"+
		      "Please do not reply this message!\n"+
                      "****************************************\n"+ content;

	    response.setContentType("text/html");
	    writer.println("<html>");
	    writer.println("<head>");
	    writer.println("<title>Sending Message Results</title>");
	    writer.println("</head>");
	    writer.println("<body><center><table><tr><td height=150 width=80%></td></tr>");

	    try {

		Context initCtx = new InitialContext();
		Context envCtx = (Context) initCtx.lookup("java:comp/env");
		Session session_m = (Session) envCtx.lookup("mail/Session");

		// Prepare our mail message
		Message message = new MimeMessage(session_m);
		message.setFrom(new InternetAddress(from));
		InternetAddress dests[] = new InternetAddress[] { new InternetAddress(to) };
		message.setRecipients(Message.RecipientType.TO, dests);
		message.setSubject(subject);
		message.setContent(content, "text/plain");
		
		// Send our mail message
		try{
		    Transport.send(message);
		}
		catch(SendFailedException sme) {
		    writer.println("<tr><td><strong>ERROR:MAIL100</strong></td></tr>");
		    writer.println("<tr><td><strong>ERROR:MAIL100</strong></td></tr>");
		}
		// Report success
		writer.println("<tr><td><strong>Your message had been successfully sent to:<BR>"+to+"</strong></td></tr>");

	    } catch (Throwable t) {
		if(user_ip.startsWith(local_ips)) {
		    writer.println("<BR>This is local Only Message:");
     		    writer.println("<BR>ENCOUNTERED EXCEPTION:  " + t);
		    writer.println("<pre>");
		    t.printStackTrace(writer);
		    writer.println("</pre>");
		}
		writer.println("<tr><td><strong>ERROR:MAIL101</strong></td></tr>");
	    }
	    writer.println("</table></center></body>");
	    writer.println("</html>");        
	    return;
	}
	else {
	    return;
	}
    }
    private class SmtpAuthenticator extends Authenticator { 
	protected PasswordAuthentication getPasswordAuthentication( ){ 
	    return new PasswordAuthentication 
		("Verification", "LiNguyen5788"); 
	} 
    } 
}
